<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Controller;
use App\Http\Controllers\LibApi\StickFigureController;
use App\Models\ResourceBookRead;
use App\Models\ResourceBusinessName;
use App\Models\ResourceTotal;
use App\Models\ResourceTotalAccessNum;
use App\Models\ResourceTypeExternal;
use App\Models\ResourceUserReadBook;
use App\Validate\ResourceTotalDataValidate;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use PhpOffice\PhpSpreadsheet\Reader\Xls\MD5;

/**
 * 数字资源(各种展示数据)
 */
class ResourceTotalDataController extends Controller
{
    public $model = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new ResourceTotal();
        $this->validate = new ResourceTotalDataValidate();
    }

    /**
     * 获取外部类型列表
     * @param resource_business_id  资源商id
     * @param big_type_id  系统大类
     * @param keywords 检索数据
     * @param page 页数    默认第一页
     * @param limit 限制条数   默认 10 条
     */
    public function getResourceExternalTypeList()
    {
        $resource_business_id = $this->request->resource_business_id;
        $big_type_id = $this->request->big_type_id;
        $keywords = $this->request->keywords;
        $limit = $this->request->input('limit', 10);
        $page = $this->request->input('page', 1);

        if ($big_type_id == 999) {
            //检索汇画资源
            $stickFigureObj = new StickFigureController();
            $data = $stickFigureObj->getProductType($page, $limit);
            if ($data['code'] == 200) {
                foreach ($data['content']['data'] as $key => $val) {
                    unset($data['content']['data'][$key]['create_time']);
                    unset($data['content']['data'][$key]['web_img']);
                    unset($data['content']['data'][$key]['pid']);
                    unset($data['content']['data'][$key]['serial_number']);
                    unset($data['content']['data'][$key]['level']);
                    unset($data['content']['data'][$key]['intro']);
                }
                return $this->returnApi(200, '获取成功', true, $data['content']);
            }
            return $this->returnApi($data['code'], $data['msg']);
        } else {
            $resourceTypeExternalModel = new ResourceTypeExternal();
            $res = $resourceTypeExternalModel->getResourceTypeList($resource_business_id, $big_type_id, $keywords, 1, $limit);
            if (empty($res['data'])) {
                return $this->returnApi(203, '暂无数据');
            }
            foreach ($res['data'] as $key => $val) {
                unset($res['data'][$key]['create_time']);
            }
            $res = $this->disPageData($res);
            return $this->returnApi(200, '获取成功', true, $res);
        }
    }

    /**
     * 获取用户历史阅读
     * @param resource_business_id  资源商id
     * @param keywords 检索数据
     * @param token  用户token
     * @param page 页数    默认第一页
     * @param limit 限制条数   默认 10 条
     */

    public function getUserReadBookHistory()
    {
        $resource_business_id = $this->request->resource_business_id;
        $keywords = $this->request->keywords;
        $user_id = $this->request->user_info['id'];
        $page = intval($this->request->input('page', 1)) ?: 1;
        $limit = intval($this->request->input('limit', 10)) ?: 10;

        $resourceUserReadBookModel = new ResourceUserReadBook();
        $res = $resourceUserReadBookModel->getUserReadBookHistory($resource_business_id, $user_id, $keywords, $limit);
        if ($res['data']) {
            $res = $this->disPageData($res);
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 获取资源商列表
     * @param page 页数    默认第一页
     * @param limit 限制条数   默认 10 条
     */
    public function getResourceBusinessList()
    {
        $page = intval($this->request->input('page', 1)) ?: 1;
        $limit = intval($this->request->input('limit', 10)) ?: 10;

        //以资源商显示数据
        $resourceBusinessNameModel = new ResourceBusinessName();
        $res = $resourceBusinessNameModel->lists(['keywords' => '', 'limit' => $limit]);
        if ($res['data']) {
            $res = $this->disPageData($res);
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }



    /**
     * 根据资源商id获取书籍列表
     * @param resource_business_id  资源商id
     * @param big_type_id  资源类型id  未传表示全部  （大类）
     * @param page 页数    默认第一页
     * @param limit 限制条数   默认 10 条
     */
    public function getResourceBusinessBookList()
    {
        $resource_business_id = $this->request->resource_business_id;
        $big_type_id = $this->request->big_type_id;
        $page = intval($this->request->input('page', 1)) ?: 1;
        $limit = intval($this->request->input('limit', 10)) ?: 10;
        if (empty($resource_business_id)) {
            return $this->returnApi(201, '资源商id不能为空');
        }

        //以资源商显示数据
        $resourceBusinessTypeModel = new ResourceBusinessName();
        $res = $resourceBusinessTypeModel->getResourceBusinessDataByBusinessId(null, $resource_business_id, $big_type_id, null,$page, $limit);
        if ($res['data']) {
            $res = $this->disPageData($res);
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 获取阅读榜单
     * @param start_time 开始时间
     * @param end_time 结束时间
     * @param type 以不同时间形式展示数据 year month week day  类型和时间一起上传，默认以类型为准
     * @param resource_business_id  资源商id
     * @param big_type_id 系统大类
     * @param page 页数    默认第一页
     * @param limit 限制条数   默认 10 条
     */
    public function getReadBookRank()
    {
        $resource_business_id = $this->request->resource_business_id;
        $big_type_id = $this->request->big_type_id;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $type = $this->request->type;
        $page = intval($this->request->input('page', 1)) ?: 1;
        $limit = intval($this->request->input('limit', 10)) ?: 10;

        //以资源商显示数据
        $resourceTotalAccessNumModel = new ResourceTotalAccessNum();
        $res = $resourceTotalAccessNumModel->getReadAccessRank($start_time, $end_time, $type, $resource_business_id, $big_type_id, $limit);
        if ($res['data']) {
            $res = $this->disPageData($res);
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 添加(用户)阅读时长记录
     * @param token  用户token
     * @param content  json 格式数据  guid 为资源guid  read_duration 时长（单位分钟）  date 日期
     *
     * json 格式：[{"guid":"11111111111","read_duration":1,"date":"2025-02-09"},{"guid":"22222222222","read_duration":2,"date":"2025-02-10"}]
     * 数组格式：[
            ['guid' => '11111111111', 'read_duration' => 1, 'date' => date('Y-m-d', strtotime('-1 day'))],
            ['guid' => '22222222222', 'read_duration' => 2, 'date' => date('Y-m-d')],
        ]
     */
    public function addReadDuration()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_add_read_duration')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $user_id = $this->request->user_info['id'];
        $content = $this->request->content;

        Log::error('添加用户阅读时长');
        Log::error($content);

        //限制前台多次提交
        $key = md5($user_id . md5($content));
        $oldKey =  Cache::get($key); //没有缓存返回false
        if ($oldKey) {
            return $this->returnApi(201, "您操作的太频繁了，请稍后重试");
        } else {
            Cache::put($key, 1, 10);
        }

        $content = json_decode($content, true);
        if (empty($content)) {
            return $this->returnApi(201,  '内容格式不正确');
        }

        DB::beginTransaction();
        try {
            $resourceBookReadModel = new ResourceBookRead();
            foreach ($content as $key => $val) {
                $resource_info = ResourceTotal::where('guid', $val['guid'])->where('is_del', 1)->first();
                if ($resource_info) {
                    $resourceBookReadModel->addAllReadDuration($val['guid'], $resource_info['resource_business_id'], $resource_info['big_type_id'], $user_id, $val['read_duration'], date('Y-m-d'));
                }
            }

            DB::commit();
            return $this->returnApi(200, '添加成功', true);
        } catch (\Exception $e) {
            DB::rollback();
            return $this->returnApi(202, $e->getMessage() . $e->getFile() . $e->getLine());
        }
    }
}
